//区县列表
$.ajax({
    method: 'POST',
    url: '/csfy/intf.do',
    data: { method: 'getAddrs', parentId: 4301 },
    success: function (res) {
        var options = '<option value="">请选择</option>'
        if (res && res.code == 200) {
            (res.rows || []).forEach(countryItem => {
                options += '<option value="' + countryItem.name + '">' + countryItem.name + '</option>';
        })
        }
        $('#search-country').html(options);
    }
});
//医院列表
$.ajax({
    method: 'POST',
    url: '/csfy/intf.do',
    data: {
        method: 'getCustomers',
        addressCity: '长沙市',
    },
    success: function (res) {
        if (res && res.code == 200) {
            var customerList = res.rows || [];
            var customerOptions = '<option>请选择医院</option>';
            customerList.forEach(customer => {
                customerOptions += '<option value="' + customer.customerCode + '">' + customer.customerName + '<option>';
        });
            $('#search-customer').html(customerOptions);
            //$("#search-customer option[value='34']").removeAttr("selected");//默认选中长沙市妇幼保健院
        }
    }
});

// 导出表格
function exportTable() {
    $("#mytab").table2excel({
        // exclude: ".noExl",//排除
        name: "Excel Document Name",
        filename: "免费券" + new Date().getTime() + ".xls",
        fileext: ".xls"
    });
}
//退出登录
function logout() {
    $.ajax({
        url: '/csfy/dologout.do',
        method: 'POST',
        success: function (res) {
            if (JSON.parse(res).code == 200) {
                window.location.href = "/csfy/index.do"
            }
        }
    })
}
//TODO 获取当前登录用户所在的省市区 start
//设置街道
function onSteetChange(parentId) {
    town = $("#steetSelect option[value='" + parentId + "']").text();
}
//设置地区
function onCountryChange(parentId) {
    country = $("#countrySelect option[value='" + parentId + "']").text();
    $.ajax({
        method: 'POST',
        url: '/csfy/intf.do',
        data: {
            method: 'getAddrs',
            parentId,
        },
        success: (res) => {
        if (res.code == 200 && res.rows) {
        var steetList = '';
        town = '';
        res.rows.map((item, index) => {
            if (index == 0) {
            town = item.name;
        }
        steetList += '<option value="' + item.code + '">' + item.name + '</option>'
    })
        $("#steetSelect").html(steetList);
    }
}
});
}

//设置转发地区下拉选项
$.ajax({
    method: 'POST',
    url: '/csfy/intf.do',
    data: { method: 'getLoginUserInfo' },
    success: res => {
    if (res.code == 10086) {
//                    window.location.href = "/csfy/index.do"
    alert("请重新登录！");
} else {
    if (res.code == 200 && res.rows) {
        $(".username").html(res.rows.userName);
        $.ajax({
            method: 'POST',
            url: '/csfy/intf.do',
            data: {
                method: 'getAddrs',
                parentId: res.rows.cityCode,
            },
            success: (res) => {
            if (res.code == 200 && res.rows) {
            var countryList = '';
            var pCode = '';
            res.rows.map((item, index) => {
                if (index == 0) {
                country = item.name;
                pCode = item.code;
            }
            countryList += '<option value="' + item.code + '">' + item.name + '</option>'
        })
            $("#countrySelect").html(countryList);
            onCountryChange(pCode);

        }
    }
    });
    }
}
}
})
//获取当前登录用户所在的省市区 end

var idCard = '';//身份证
var town = '';//街道
var country = '';//地区

//TODO 确定转发
function transpond() {
    $.ajax({
        method: 'POST',
        data: {
            method: 'savePresonInfo',
            id: idCard,
            town: town,
            country: country
        },
        url: '/csfy/intf.do',
        success: (res) => {
        if (res.code == 200) {
        $('#search-btn').trigger("click");
        alert('转发成功！');
        $('#myModal').modal('hide');
    }
}
})
}
$("body").click(function () {
    $("#id-card-photo-wrapper").hide(300);
    angle = 0;
    $("#id-card-photo").rotate(0);
})
Date.prototype.pattern = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    var week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : '') + week[this.getDay() + '']);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(('' + o[k]).length)));
        }
    }
    return fmt;
}
//根据窗口调整表格高度
$(window).resize(function () {
    $('#mytab').bootstrapTable('resetView', {
        height: tableHeight()
    })
})
//生成用户数据
$('#mytab').bootstrapTable({
    method: 'POST',
    contentType: "application/x-www-form-urlencoded",//必须要有！！！！
    url: "/csfy/intf.do?method=getDetailPresonInfos",//要请求数据的文件路径
    height: tableHeight(),//高度调整
    toolbar: '#toolbar',//指定工具栏
    striped: true, //是否显示行间隔色
    dataField: "rows",//bootstrap table 可以前端分页也可以后端分页，这里
    //我们使用的是后端分页，后端分页时需返回含有total：总记录数,这个键值好像是固定的
    //rows： 记录集合 键值可以修改  dataField 自己定义成自己想要的就好
    pageNumber: 1, //初始化加载第一页，默认第一页
    pagination: true,//是否分页
    queryParamsType: 'limit',//查询参数组织方式
    queryParams: queryParams,//请求服务器时所传的参数
    sidePagination: 'server',//指定服务器端分页
    pageSize: 10,//单页记录数
    pageList: [5, 10, 20, 30],//分页步进值
    showRefresh: true,//刷新按钮
    // showColumns: true,
    clickToSelect: true,//是否启用点击选中行
    toolbarAlign: 'left', //工具栏对齐方式
    buttonsAlign: 'left',//按钮对齐方式
    toolbar: '#toolbar',//指定工作栏
    columns: [
        {
            title: '选项',
            field: 'select',
            //复选框
            radio: true,
            width: 25,
            align: 'center',
            valign: 'middle'
        },
        {
            title: '姓名',
            field: 'name',
            //列数据格式化
            formatter: formatName
        },
        {
            title: '送检单',
            //列数据格式化
            formatter: formatAddress
        },
        {
            title: '免费券类型',
            field: 'type',
            width: 120,
        },
        {
            title: '免费类型',
            field: 'presonType',
            formatter: formatPersonType
        },
        {
            title: '身份证号',
            field: 'id',
        },
        {
            title: '样本状态',
            field: 'status',
            //列数据格式化
            formatter: formatStatus
        },
        {
            title: '申请日期',
            field: 'createTime',
            //列数据格式化
            formatter: formatDate
        },
        {
            title: '诊断',
            field: 'Attribute',
            align: 'center',
            //列数据格式化
            formatter: formatPhoto
        },
        {
            title: '检测报告',
            field: 'Attribute',
            align: 'center',
            //列数据格式化
            formatter: operateFormatter
        }
    ],
    locale: 'zh-CN',//中文支持,
    responseHandler: function (res) {
        //在ajax获取到数据，渲染表格之前，修改数据源
        return res;
    },
    onRefresh: function (params) {
        if (params && params.query) {
            return false;
        }
        $("#search-name").val('');
        $("#search-date").val('');
        $("#search-status").val('');
        $("#search-steet").val('');
        $("#search-product").val('');
        $("#search-idcard").val('');
        $("search-country").val('');
        $("#search-customer").val('');
        $("#search-coupontype").val('');
    }
});
function toDetail(id) {
    window.location.href = "/csfy/static/manage-sys/coupon-detail.html?id=" + id
}
//三个参数，value代表该列的值
function formatStatus(value, row, index) {
    value = parseInt(value);
    var text = '';
    if (!isNaN(value)) {
        if (value === 1) {
            text = '审批通过';
        } else if (value === 0) {
            text = '审批中';
        } else if (value === -1) {
            text = '未审批通过';
        }
    }
    return '<span style="color: rgba(0,0,0,.45);">' + text + '</span>';
}
//三个参数，value代表该列的值
function formatName(value, row, index) {
    return '<a href="javascript:toDetail(' + ('\'' + row.id + '\'') + ');">' + value + '</a>';
}
//三个参数，value代表该列的值
function operateFormatter(value, row, index) {
    return '<a href="javascript:setIdCard(' + ('\'' + row.id + '\'') + ');">转发</a>'
}
function setIdCard(id) {
    idCard = id;
    $('#myModal').modal('show')
}
//三个参数，value代表该列的值
function formatAddress(value, row, index) {
    return (row.city || '') + (row.country || '') + (row.town || '');
}
//三个参数，value代表该列的值
function formatDate(value, row, index) {
    var time = Date.parse(value);
    var date = new Date(time);
    return date.pattern("yyyy-MM-dd hh:mm:ss")
}
//三个参数，value代表该列的值
function formatPersonType(value, row, index) {
    //优惠类型
    var type = parseInt(value);
    var text = '其他免费类型';
    if (isNaN(type)) {
    } else {
        if (type === 1) {
            text = '本人为长沙户口';
        } else if (type === 2) {
            text = '配偶为长沙户口';
        } else if (type === 3) {
            text = '长沙居住证';
        } else if (type === 4) {
            text = '军人及军人配偶';
        }
    }
    return '<span style="color: rgba(0,0,0,.45);">' + text + '</span>';
}
function toSeeIdCardPhoto(photoUrl) {
    $("#id-card-photo").attr('src', photoUrl);
    $("#id-card-photo-wrapper").show(300);
}
//三个参数，value代表该列的值
function formatPhoto(value, row, index) {
    return '<a href="javascript:toSeeIdCardPhoto(' + ("'" + row.cardFrontImgUrl) + "'" + ');">查看</a>';
}
//请求服务数据时所传参数
function queryParams(params) {
    return {
        //每页多少条数据
        rows: params.limit,
        //请求第几页
        page: params.pageNumber,
    }
}
//查询按钮事件
$('#search-btn').click(function () {
    var name = $("#search-name").val() || '';
    var createTime = $("#search-date").val() || '';
    var status = $("#search-status").val() || '';
    var town = $("#search-steet").val() || '';
    var productName = $("#search-product").val() || '';
    var id = $("#search-idcard").val() || '';
    //区/县
    var country = $("#search-country").val() || '';
    //送检医院
    var customerCode = $("#search-customer").val() || '';
    //优惠券类型
    var productCode = $("#search-coupontype").val() || '';

    var query = {};
    if (name != '') {
        query.name = name;
    }
    if (createTime != '') {
        query.createTime = createTime;
    }
    if (status != '') {
        query.status = status;
    }
    if (town != '') {
        query.town = town;
    }
    if (productName != '') {
        query.productName = productName;
    }
    if (id != '') {
        query.id = id;
    }
    //区/县
    if (country != '') {
        query.country = country;
    }
    //送检医院
    if (customerCode != '') {
        query.customerCode = customerCode;
    }
    //优惠券类型
    if (productCode != '') {
        query.productCode = productCode;
    }
    $('#mytab').bootstrapTable('refresh', { url: '/csfy/intf.do?method=getDetailPresonInfos', query });
})
//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 280;
}
$("#btn_add").click(function () {
    //TODO
    window.location.href = "/csfy/static/manage-sys/coupon-apply.html"
});
//批量审批，身份证列表
var idList = [];
function agreeList() {
    var rows = $("#mytab").bootstrapTable('getSelections');
    if (!rows || rows.length === 0) {
        alert('未选中操作的行');
    } else {
        var agreeList = '';
        idList.length = 0;
        rows.map(item => {
            idList.push(item.id);
        if (item.couponInfos && item.couponInfos.length && item.couponInfos.length > 0) {
            var couponList = [];
            item.couponInfos.forEach(couponItem => couponList.push(couponItem.couponName));
            agreeList += '<p class="agree-item">' + (item.name + '，' + item.id + '，' + item.address + '，免费券：' + couponList.join("、")) + '</p>';
        } else {
            agreeList += '<p class="agree-item">' + (item.name + '，' + item.id + '，' + item.address + '，免费券：无') + '</p>';
        }
    });
        $(".agree-list").html(agreeList);
        $('#agreeModel').modal('show');
    }
}
var angle = 0;
$("#ic-rotate").bind("click", function (event) {
    event.stopPropagation();
    $("#id-card-photo").rotate({
        angle: angle,
        animateTo: angle + 90,
        duration: 300,
        callback: function () { angle += 90 }
    });
});
//同意——批量审批
function agree() {
    $("#agreeModel").modal('hide');

    var promise = new Promise(function (resolve, reject) {
        var index = 0;
        var success = true;
        idList.map(id => {
            $.ajax({
            url: '/csfy/intf.do',
            method: 'POST',
            data: { method: 'savePresonInfo', id: id, status: '1' },
            success: function (res) {
                success = res.code == 200;
                index++;
                if (index == idList.length) {
                    if (success) {
                        resolve('操作成功');
                    } else {
                        reject('操作失败');
                    }
                }
            }, error: function (msg) {
                index++;
                if (index == idList.length) {
                    reject('操作失败');
                }
            }
        })
    });
    });

    promise.then(function (value) {
        alert(value);
    }, function (value) {
        alert(value);
    });
}
//不同意——批量审批
function disAgree() {
    $("#agreeModel").modal('hide');

    var promise = new Promise(function (resolve, reject) {
        var index = 0;
        var success = true;
        idList.map(id => {
            $.ajax({
            url: '/csfy/intf.do',
            method: 'POST',
            data: { method: 'savePresonInfo', id: id, status: '-1' },
            success: function (res) {
                success = res.code == 200;
                index++;
                if (index == idList.length) {
                    if (success) {
                        resolve('操作成功');
                    } else {
                        reject('操作失败');
                    }
                }
            }, error: function (msg) {
                index++;
                if (index == idList.length) {
                    reject('操作失败');
                }
            }
        })
    });
    });

    promise.then(function (value) {
        alert(value);
    }, function (value) {
        alert(value);
    });
}